/* eslint-disable no-param-reassign */
const axios = require("axios");
const qs = require("qs");
const storeManage = require("../utils/store-manage"); // 引入全局token存储模块

const http = axios.create({
  timeout: 120 * 1000,
  transformRequest: [
    function (data) {
      return JSON.stringify(data);
    },
  ],
});

// http request 拦截器
http.interceptors.request.use(
  (config) => {
    config.headers = {
      "Content-Type": "application/json;",
    };

    // 从全局token存储中获取token
    const token = storeManage.getStore().token;
    if (token) {
      // 检查URL是否已经包含token参数
      if (!config.url.includes("token=")) {
        config.url += (config.url.includes("?") ? "&" : "?") + `token=${token}`;
      }
    }

    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// http response 拦截器
http.interceptors.response.use(
  (response) => {
    if (response.status < 400) {
      // 400003状态码：服务端拒绝访问，目前用于考试屏蔽中的教室获取流的接口 401:未授权
      if (
        response.data.code === 0 ||
        response.data.status === 0 ||
        response.data.status === 400003 ||
        response.data.status === 401
      ) {
        return Promise.resolve(response.data);
      }
      if (response.data.code === 302 || response.data.status === 302) {
        // 登录
      }
      return Promise.reject(response.data);
    }
    return Promise.reject();
  },
  () => {
    return Promise.reject();
  }
);

const formDataHttp = axios.create({
  timeout: 30000,
  transformRequest: [
    function (data) {
      return qs.stringify(data);
    },
  ],
});

// http request 拦截器
formDataHttp.interceptors.request.use(
  (config) => {
    config.headers = { "Content-Type": "application/x-www-form-urlencoded" };

    // 从全局token存储中获取token，排除登录和获取公钥接口
    if (
      !config.url.includes("/login") &&
      !config.url.includes("/getPublicKey")
    ) {
      const token = storeManage.getStore().token;
      if (token) {
        // 检查URL是否已经包含token参数
        if (!config.url.includes("token=")) {
          config.url +=
            (config.url.includes("?") ? "&" : "?") + `token=${token}`;
        }
      }
    }

    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// http response 拦截器
formDataHttp.interceptors.response.use(
  (response) => {
    if (response.status < 400) {
      // 400003状态码：服务端拒绝访问，目前用于考试屏蔽中的教室获取流的接口 401:未授权
      if (
        response.data.code === 0 ||
        response.data.status === 0 ||
        response.data.status === 400003 ||
        response.data.status === 401
      ) {
        return Promise.resolve(response.data);
      }
      if (response.data.code === 302 || response.data.status === 302) {
        // 登录
      }
      return Promise.reject(response.data);
    }
    return Promise.reject();
  },
  () => {
    return Promise.reject();
  }
);

module.exports = { http, formDataHttp };
